package com.eien.phonezwei.service;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.widget.Toast;

import com.eien.phonezwei.utils.ZUtil;

/**
 * 转发短信服务
 *
 * @author honooon
 */
public class PhoneZweiService extends Service {

    SharedPreferences eSharedPreferences;
    private static long SEND_INTERVAL = 90 * 1000; // 1.5分钟内不发送
    // private final long SEND_INTERVAL = 10 * 1000; // 5分钟内不发送

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        // eSharedPreferences = getSharedPreferences("PhoneZweiConfig", 0);
        eSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (eSharedPreferences.getBoolean("forwardMissedCall", false)) {
            long lastSend = eSharedPreferences.getLong("lastSend", 0);
            if (System.currentTimeMillis() - lastSend >= SEND_INTERVAL) {
                int missCallCount = ZUtil.readMissedCall(this);
                System.out.println("未接来电数量：" + missCallCount);
                if (missCallCount > 0) {
                    String sendToNumber = eSharedPreferences.getString("sendToNumber", "");
                    if (sendToNumber.equals("")) {
                        Toast.makeText(this, "转发失败，目标手机号码不能为空！", Toast.LENGTH_LONG).show();
                    } else {
                        String missedStr = ZUtil.missedCallToString(this);
                        String text = "你有来自" + missedStr + "的共" + missCallCount + "条未接来电！";
                        if (missedStr.equals("")) {
                            text = "你有" + missCallCount + "条未接来电！";
                        }
                        System.out.println(text);
                        ZUtil.sendSMS(this, sendToNumber, text);
                    }
                    SharedPreferences.Editor mEditor = eSharedPreferences.edit();
                    mEditor.putLong("lastSend", System.currentTimeMillis());
                    mEditor.apply();
                }
            }
        }
        stopSelf();
        return super.onStartCommand(intent, flags, startId);
    }

}
